﻿using System;
using System.Collections.Concurrent;

namespace Devme.Diagnostics
{
    public static class StopwatchManager
    {
        private static IStopwatchFactory _factory = new DefaultStopwatchFactory();
        public static IStopwatchFactory Factory
        {
            get { return _factory; }
            set { _factory = value; }
        }

        static readonly ConcurrentDictionary<string, StopwatchContext> Shared = new ConcurrentDictionary<string, StopwatchContext>();

        public static IDisposable Start(StopwatchResultHandler<TimeSpan> handler)
        {
            return new StopwatchScope(Factory, handler);
        }

        public static IDisposable Start(string name, StopwatchResultHandler<StopwatchResult> handler)
        {
            return new StopwatchScope
                (
                Factory,
                elapsed =>
                {
                    StopwatchContext context = Shared.GetOrAdd(name, CreateNewContext);
                    StopwatchResult result = context.Refresh(elapsed);
                    handler(result);
                });
        }

        static StopwatchContext CreateNewContext(string name)
        {
            return new StopwatchContext(name);
        }
    }
}